package com.example.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.common.Re;
import com.example.entity.User;
import com.example.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息
 * </p>
 *
 * @author czx
 * @since 2022-04-28
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机短信验证码
     *
     * @param user 用户
     * @return 结果
     */
    @PostMapping("/sendMsg")
    public Re<String> sendMsg(@RequestBody User user) {
        int code = userService.sendMsg(user);
        String phone = user.getPhone();
        if (code != 0) {
            // 将短信验证码存到session
//            session.setAttribute(phone, code);
            // 将生成的验证码缓存到Redis中，并且设置有效期为5分钟
            stringRedisTemplate.opsForValue().set(phone, String.valueOf(code), 5, TimeUnit.MINUTES);
            return Re.success("手机验证码短信发送成功");
        }
        return Re.error("短信发送失败");
    }

    /**
     * 发送邮件验证码
     *
     * @param user 用户
     * @return 结果
     */
    @PostMapping("/sendMail")
    @CachePut(value = "userCache",key = "#user.email",cacheManager = "redisCacheManager5M")
    public Re<String> sendMail(@RequestBody User user) {
        String email = user.getEmail();
        String code = userService.sendMail(email);
        if (StringUtils.isNotEmpty(code)) {
            return Re.success("邮件发送成功");
        }
        return Re.error("邮件发送失败");
    }

    /**
     * 登录
     *
     * @param map     传过来的数据
     * @param session session会话对象
     * @return 结果
     */
    @PostMapping("/login")
    public Re<String> login(@RequestBody Map<String,String> map, HttpSession session) {
        log.info("验证码登录：{}", map.toString());
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        String code = null;
        if (map.get("code") != null) {
            code = map.get("code");
        }
        //从redis中获取保存的验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get(phone);

        User user = null;
        if ((codeInRedis != null && codeInRedis.equals(code))) {
            user = userService.login(phone, null, null);
        }
        if (user != null) {
            session.setAttribute("user", user.getId());
            // 如果用户登录成功,删除Redis中缓存的验证码
            stringRedisTemplate.delete(phone);
            return Re.success("登录成功");
        }
        return Re.error("登录失败");
    }

    /**
     * 登录
     *
     * @param map     传过来的数据
     * @param session session会话对象
     * @return 结果
     */
    @PostMapping("/mailLogin")
    public Re<String> mailLogin(@RequestBody Map<String,String> map, HttpSession session) {
        log.info("邮箱验证码登录：{}", map.toString());
        //获取手机号
        String phone = map.get("phone");
        //获取邮箱
        String email = map.get("email");
        //获取验证码
        String code = null;
        if (map.get("code") != null) {
            code = map.get("code");
        }
        //从redis中获取保存的验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get(email);
        User user = null;
        if ((codeInRedis != null && codeInRedis.equals(code))) {
            user = userService.login(phone, email, null);
        }
        if (user != null) {
            session.setAttribute("user", user.getId());
            // 如果用户登录成功,删除Redis中缓存的验证码
            stringRedisTemplate.delete(email);
            return Re.success("登录成功");
        }
        return Re.error("登录失败");
    }

    /**
     * 密码登录
     *
     * @param user    用户
     * @param session session
     * @return 结果
     */
    @PostMapping("/pwdLogin")
    public Re<String> pwdLogin(@RequestBody User user, HttpSession session) {
        log.info("密码登录：{}", user.toString());
        String phone = user.getPhone();
        String password = user.getPassword();
        User save = userService.login(phone, null, password);
        if (save != null) {
            session.setAttribute("user", save.getId());
            return Re.success("登录成功");
        }
        return Re.error("登录失败");
    }


    /**
     * 退出登录
     *
     * @param request 页面请求
     * @return 结果
     */
    @PostMapping("/logout")
    public Re<String> loginOut(HttpServletRequest request) {
        log.info("退出登录... ");
        request.getSession().removeAttribute("user");
        return Re.success("退出登录");
    }

    /**
     * 根据传过来的条件查询用户
     *
     * @param user 用户id
     * @return 查询结果
     */
    @PostMapping
    public Re<User> getById(@RequestBody User user) {
        log.info("用户查询中... user = {}", user);
        User one = userService.getByIdOrPhone(user);
        if (one != null) {
            return Re.success(one);
        }
        return Re.error("用户查询失败");
    }

    /**
     * 用户修改信息
     *
     * @param user 用户
     * @return 结果
     */
    @PutMapping
    public Re<String> update(@RequestBody User user) {
        boolean update = userService.updateUserInfo(user);
        if (update) {
            return Re.success("修改个人信息成功");
        }
        return Re.error("修改个人信息失败");
    }
}
